﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using UpdateFileName.Models;

namespace UpdateFileName.Controller
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {

        private readonly string SessionFile = "session.config";

        private Guid lastid;

        [HttpGet]
        public List<FolderInfo> GetList([FromQuery] FolderRequest request)
        {

            if (!Directory.Exists($"{request.folder}") || string.IsNullOrEmpty(request.folder))
            {
                throw new Exception($"url not correct");
            }


            var list = FillFolders(request.folder);

            foreach (var item in list)
            {
                item.children = FillFolders(item.folder);
            }

            return list;
        }


        private List<FolderInfo> FillFolders(string f)
        {

            var list = new List<FolderInfo>();

            var folders = Directory.GetDirectories(f, $"*", SearchOption.TopDirectoryOnly);


            foreach (var folder in folders)
            {

                FolderInfo info = new FolderInfo();

                info.Id = GenernateGuid();

                DirectoryInfo d = new DirectoryInfo(folder);

                info.label = d.Name;

                info.folder = folder;

                list.Add(info);
            }

            return list;

        }


        [HttpGet]
        public List<FolderFileInfo> GetFileList([FromQuery] FolderRequest request)
        {

            var files = Directory.GetFiles(request.folder, string.Empty, SearchOption.TopDirectoryOnly);

            var list = new List<FolderFileInfo>();

            foreach (var file in files)
            {
                if (!(
                       file.ToLower().EndsWith(".mp4") ||
                       file.ToLower().EndsWith(".rm") ||
                       file.ToLower().EndsWith(".rmvb") ||
                       file.ToLower().EndsWith(".mpg") ||
                       file.ToLower().EndsWith(".m4v") ||
                       file.ToLower().EndsWith(".avi") ||
                       file.ToLower().EndsWith(".mkv") ||
                       file.ToLower().EndsWith(".flv") ||
                       file.ToLower().EndsWith(".mpeg") ||
                       file.ToLower().EndsWith(".mpeg")
                       ))
                {
                    continue;
                }

                list.Add(new FolderFileInfo(file));
            }

            return list;
        }


        [HttpPost]
        public string ReNameFiles(ReNameFileRequest request)
        {

            if (request.fileInfos == null || request.fileInfos.Count() < 1) return "无匹配文件";

            foreach (var fileinfo in request.fileInfos)
            {
                try
                {
                    FileInfo f = new FileInfo(fileinfo.filefullname);

                    Console.WriteLine($"{fileinfo.filefullname}->{Path.Combine(f.DirectoryName, fileinfo.newfilename)}");

                    f.MoveTo(Path.Combine(f.DirectoryName, fileinfo.newfilename));
                }
                catch (Exception ex)
                {
                    return $"{ex.Message}";
                }
            }

            return "更新成功";
        }

        [HttpPost]
        public bool SaveSession(SaveSessionRequest request)
        {

            if (string.IsNullOrEmpty(request.Folder)) return false;

            System.IO.File.WriteAllText(SessionFile, request.Folder,Encoding.UTF8);

            return true;
        }



        [HttpGet]
        public InitfoldersResult Initfolders() {

            if (!System.IO.File.Exists(SessionFile)) {
                var list = GetList(new FolderRequest { folder = "/pf" });
                return new InitfoldersResult { folderInfos = list, lastid = lastid.ToString() };
            }
            // /pf 默认路径
            var folder = System.IO.File.ReadAllText(SessionFile,Encoding.UTF8);

            if (string.IsNullOrEmpty(folder))
            {
                var list =  GetList(new FolderRequest { folder = "/pf" });
                return new InitfoldersResult { folderInfos = list, lastid = lastid.ToString() };
            }
            else {

                var list = new List<FolderInfo>();

                var fs = folder.Split("/");

                foreach (var item in fs)
                {
                    if (string.IsNullOrEmpty(item)) continue;

                    if (list.Count < 1) {

                        list = GetList(new FolderRequest { folder = $"/{item}" });
                        break;
                    }

                }

                FillDepthByFolder(list, folder);

                return new InitfoldersResult { folderInfos = list, lastid = lastid.ToString() };
            }

        }

        private void FillDepthByFolder(List<FolderInfo> list,string folder) {

            if (list == null || list.Count < 1) return;

            foreach (var item in list)
            {
                if (folder.StartsWith(item.folder))
                {
                    item.children = FillFolders(item.folder);

                    FillDepthByFolder(item.children, folder);
                }
            }

        }

        private Guid GenernateGuid() {

            lastid = Guid.NewGuid();

            return lastid;
        }
    }
}
